<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="productCode" label="产品编码">
        <el-input v-model="dataForm.productCode" placeholder="产品编码"></el-input>
      </el-form-item>
      <el-form-item prop="productName" label="产品名称">
        <el-input v-model="dataForm.productName" placeholder="产品名称"></el-input>
      </el-form-item>
      <el-form-item prop="category" label="产品类型">
        <el-select v-model="dataForm.category" placeholder="产品类型">
          <el-option v-for="product in productList" :key="product.categorySign" :label="product.categoryName" :value="product.categorySign"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="productImage" label="产品图片">
        <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeImageUpload">
          <img v-if="dataForm.productImage" :src="dataForm.productImage" class="avatar" />
          <el-icon class="avatar-uploader-icon" v-else><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="productDesc" label="产品描述">
        <el-input v-model="dataForm.productDesc" placeholder="产品描述"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import axios from "axios";
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const productList = ref<any[]>([]);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  productCode: "",
  productName: "",
  category: "",
  productImage: "",
  productDesc: "",
  realImageName: ""
});

const rules = ref({
  productCode: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  productName: [{ required: true, message: "必填项不能为空", trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";
  dataForm.productName = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getTypeList()]).then(() => {
    if (id) {
      getInfo(id);
    }
  });
};

const beforeImageUpload = (file: any) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error({
      message: "上传头像图片大小不能超过 2MB!"
    });
    return;
  }

  baseService.post("/image/pre/url", { fileName: file.name }).then((res) => {
    if (res?.data?.src) {
      getFileBinary(file, res.data.src, res.data.realName);
    }
  });
  return false;
};

const getFileBinary = (file: any, uploadUrl: string, realName: string) => {
  axios({
    method: "put",
    url: uploadUrl,
    headers: {
      "Content-Type": "application/octet-stream"
    },
    data: file
  })
    .then((response) => {
      const { status } = response;
      if (status === 200) {
        dataForm.realImageName = realName;
        dataForm.productImage = URL.createObjectURL(file);
      }
    })
    .catch(() => {});
};

// 获取产品类型选项
const getTypeList = () => {
  return baseService.get("/alarm/product/category/list").then((res) => {
    productList.value = res.data;
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get(`/alarm/product/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/alarm/product", {
      ...dataForm
    }).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
